<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ref, unref, watch, reactive, computed } from 'vue'
import {
  ElTree,
  ElInput,
  ElDivider,
  ElTag,
  ElPopover,
  ElLink,
  ElTable,
  ElTableColumn,
  ElMessage,
  ElDialog,
  ElButton,
  ElMessageBox
} from 'element-plus'
import {
  getTaskPoolApi,
  putTaskPoolApi,
  getTaskGroupTreeApi,
  getTaskStatusOptionApi,
  exportTaskPoolApi,
  addTaskPoolApi,
  syncTasksApi,
  deleteTaskPoolApi,
  queryTaskApi,
  exportQueryListApi
} from '@/api/dispatch/taskpool'
import { TaskType, TaskGroupType } from '@/api/dispatch/taskpool/types'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useForm } from '@/hooks/web/useForm'
import { FormSchema } from '@/components/Form'
import { useEventBus } from '@/hooks/event/useEventBus'
import TicketTable from './components/TicketTable.vue'
import Write from './components/Write.vue'
import Import from './components/Import.vue'
import Feedback from './Feedback/Feedback.vue'
import Assign from './AssignUser/Assign.vue'
import Need from './Need/Need.vue'
import Team from './WorkTeam/Team.vue'
import Sync from './components/Sync.vue'
import { Icon } from '@iconify/vue'

const { t } = useI18n()

const ids = ref<number[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getTaskPoolApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data || [],
      total: res.count || 0
    }
  },
  fetchExportApi: async (headers) => {
    const { pageSize, currentPage } = tableState
    const res = await exportQueryListApi(
      {
        page: unref(currentPage),
        limit: unref(pageSize),
        ...unref(searchParams)
      },
      headers
    )
    return res
  },
  fetchDelApi: async () => {
    const res = await deleteTaskPoolApi(unref(ids))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, exportQueryList, getElTableExpose, delList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  // {
  //   field: 'selection',
  //   type: 'expand',
  //   slots: {
  //     default: (data) => <Write ref="writeRef" currentRow={data.row} />
  //   }
  // },
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'index',
    label: t('common.index'),
    type: 'index'
  },
  {
    field: 'ticket_id',
    label: '工单号',
    minWidth: '170px',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElLink onClick={() => action(data.row, 'edit')}>{data.row.ticket_id}</ElLink>
          </>
        )
      }
    }
  },
  {
    field: 'ao_id',
    label: 'AO编号',
    minWidth: '130px'
  },
  {
    field: 'ao_name',
    label: 'AO名称',
    minWidth: '140px'
  },
  {
    field: 'ao_type',
    label: 'AO类型',
    minWidth: '70px'
  },
  {
    field: 'status',
    label: 'AO状态',
    minWidth: '80px'
  },
  {
    field: 'product_type',
    label: '机型',
    minWidth: '70px'
  },
  {
    field: 'flight',
    label: '架次',
    minWidth: '70px'
  },
  {
    field: 'station',
    label: '工位',
    minWidth: '60px'
  },
  {
    field: 'sub_station',
    label: '二级工位',
    minWidth: '70px'
  },
  {
    field: 'team',
    label: '班组',
    minWidth: '80px'
  },
  {
    field: 'team_leader',
    label: '班组长',
    minWidth: '120px'
  },
  {
    field: 'work_teams',
    label: '外协信息',
    minWidth: '70px',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElPopover
              trigger="click"
              width="800px"
              v-slots={{
                reference: () => {
                  return (
                    <ElLink>
                      {data.row?.work_teams && data.row.work_teams.length > 0 ? (
                        <ElTag type="success">{data.row.work_teams.length} 项</ElTag>
                      ) : (
                        <ElTag type="info">无</ElTag>
                      )}
                    </ElLink>
                  )
                },
                default: () => {
                  return <Team data={data.row.work_teams} ticketId={data.row.ticket_id} />
                }
              }}
            />
          </>
        )
      }
    }
  },
  {
    field: 'needs',
    label: '辅料信息',
    minWidth: '70px',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElPopover
              trigger="click"
              width="800px"
              v-slots={{
                reference: () => {
                  return (
                    <ElLink>
                      {data.row?.needs && data.row.needs.length > 0 ? (
                        <ElTag type="success">{data.row.needs.length} 项</ElTag>
                      ) : (
                        <ElTag type="info">无</ElTag>
                      )}
                    </ElLink>
                  )
                },
                default: () => {
                  return <Need data={data.row.needs} ticketId={data.row.ticket_id} />
                }
              }}
            />
          </>
        )
      }
    }
  },
  {
    field: 'group1',
    label: '标签',
    minWidth: '70px'
  },
  {
    field: 'in_daily_plan',
    label: '日计划',
    minWidth: '60px',
    slots: {
      default: (data: any) => {
        return (
          <>
            {data.row?.in_daily_plan ? (
              <ElTag type="success">√</ElTag>
            ) : (
              <ElTag type="danger">x</ElTag>
            )}
          </>
        )
      }
    }
  },
  {
    field: 'in_weekly_plan',
    label: '周计划',
    minWidth: '60px',
    slots: {
      default: (data: any) => {
        return (
          <>
            {data.row?.in_weekly_plan ? (
              <ElTag type="success">√</ElTag>
            ) : (
              <ElTag type="danger">x</ElTag>
            )}
          </>
        )
      }
    }
  },
  {
    field: 'assign_users',
    label: '派工人员',
    minWidth: '60px',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElPopover
              trigger="click"
              width="800px"
              v-slots={{
                reference: () => {
                  return (
                    <ElLink>
                      {data.row?.assign_users && data.row.assign_users.length > 0 ? (
                        <ElTag type="primary"> {data.row.assign_users.length} 人</ElTag>
                      ) : (
                        <ElTag type="warning">无</ElTag>
                      )}
                    </ElLink>
                  )
                },
                default: () => {
                  return <Assign data={data.row} ticketId={data.row.ticket_id} />
                }
              }}
            />
          </>
        )
      }
    }
  },
  {
    field: 'material_match',
    label: '物料配套',
    minWidth: '60px',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElLink href={'/logistics/delivery/detail?serNo=' + data.row.ticket_id} target="blank">
              {data.row?.material_match ? (
                <ElTag type="success">√</ElTag>
              ) : (
                <ElTag type="danger">x</ElTag>
              )}
            </ElLink>
          </>
        )
      }
    }
  },
  {
    field: 'delivery_message',
    label: '配送通知',
    minWidth: '60px',
    slots: {
      default: (data: any) => {
        return (
          <>
            {data.row?.delivery_message ? (
              <ElTag type="success">√</ElTag>
            ) : (
              <ElTag type="danger">x</ElTag>
            )}
          </>
        )
      }
    }
  },
  {
    field: 'pi',
    label: '质保标注',
    minWidth: '60px',
    slots: {
      default: (data: any) => {
        return (
          <>{data.row?.pi ? <ElTag type="success">√</ElTag> : <ElTag type="danger">x</ElTag>}</>
        )
      }
    }
  },
  {
    field: 'feedback',
    label: '问题',
    minWidth: '60px',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElPopover
              trigger="click"
              width="800px"
              v-slots={{
                reference: () => {
                  return (
                    <ElLink>
                      {data.row?.feedback && data.row.feedback.length > 0 ? (
                        <ElTag type="danger">{data.row.feedback.length} 条</ElTag>
                      ) : (
                        <ElTag type="success">无</ElTag>
                      )}
                    </ElLink>
                  )
                },
                default: () => {
                  return <Feedback data={data.row.feedback} ticketId={data.row.ticket_id} />
                }
              }}
            />
          </>
        )
      }
    }
  },
  {
    field: 'create_datetime',
    label: '创建时间',
    minWidth: '140px'
  }
])

const { formRegister, formMethods } = useForm()
const { setValues } = formMethods

const queryLoading = ref(false)
const ticketOptions = ref([])
const ticketRemoteMethod = async (query: string) => {
  if (query) {
    queryLoading.value = true
    try {
      const res = await queryTaskApi({ ticket_id: query })
      if (res) {
        ticketOptions.value = res.data
      }
    } finally {
      queryLoading.value = false
    }
  } else {
    ticketOptions.value = []
  }
}

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'group_id',
    label: '分组',
    component: 'Input'
  },
  {
    field: 'ao_id',
    label: 'AO编号',
    component: 'Input'
  },
  {
    field: 'ao_name',
    label: 'AO名称',
    component: 'Input'
  },
  {
    field: 'ao_type',
    label: 'AO类型',
    component: 'Input'
  },
  {
    field: 'status',
    label: 'AO状态',
    component: 'Select',
    componentProps: {
      multiple: false,
      collapseTags: true,
      maxCollapseTags: 1
    },
    optionApi: async () => {
      const res = await getTaskStatusOptionApi()
      return res.data
    }
  },
  {
    field: 'ticket_id',
    label: '工单号',
    component: 'Select',
    componentProps: {
      filterable: true,
      remote: true,
      remoteMethod: ticketRemoteMethod,
      remoteShowSuffix: true,
      loading: queryLoading,
      options: ticketOptions
    }
  },
  {
    field: 'team_leader',
    label: '班组长',
    component: 'Input'
  },
  {
    field: 'plan_user',
    label: '计划人员',
    component: 'Input'
  },
  {
    field: 'plan_start',
    label: '计划开始日期',
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    field: 'plan_end',
    label: '预计归档日期',
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    field: 'start',
    label: '实际开工时间',
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    field: 'end',
    label: '实际归档日期',
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    field: 'is_not_assign',
    label: '未派工',
    component: 'Switch'
  }
])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

// ###########################################
//############### 分组树 ######################
const treeEl = ref<typeof ElTree>()

const groupTree = ref<TaskGroupType[]>([])
const fetchTaskGroupTree = async () => {
  const res = await getTaskGroupTreeApi({})
  groupTree.value = res.data
}
fetchTaskGroupTree()

const currentGroup = ref('')
watch(
  () => currentGroup.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: TaskGroupType) => {
  setValues({ group_id: data.id })
}

const filterNode = (value: string, data: TaskGroupType) => {
  if (!value) return true
  return data.name.includes(value)
}

// 折叠分组树
const isCollpase = ref(false)
const collapseBtnClass = computed(() => (isCollpase.value ? 'el-tree-unfold' : 'el-tree-fold'))
useEventBus({
  name: 'updateTask',
  callback: async () => {
    getList()
  }
})
// ############### 结束分组树 ##################
// ###########################################

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TaskType>()
const actionType = ref('')

const action = (row: TaskType | undefined, type: string) => {
  dialogTitle.value = t(`common.${type}`)
  actionType.value = type
  if (row) currentRow.value = { ...row }
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()
const saveLoading = ref(false)

const save = async () => {
  saveLoading.value = true
  try {
    if (actionType.value === 'edit') {
      const res = await putTaskPoolApi({
        id: currentRow.value?.id,
        ...(await unref(writeRef)?.submit())
      })
      if (res) {
        // dialogVisible.value = false
        getList()
        ElMessage.success('保存成功')
      }
    } else if (actionType.value === 'add') {
      const res = await addTaskPoolApi(await unref(writeRef)?.submit())
      if (res) {
        dialogVisible.value = false
        ElMessage.success(res.data)
        getList()
      }
    }
  } finally {
    saveLoading.value = false
  }
}

// 同步任务
const syncLoading = ref(false)
const syncDialog = ref(false)
const syncTasks = async () => {
  syncLoading.value = true
  try {
    const res = await syncTasksApi(await unref(writeRef)?.submit())
    if (res) {
      ElMessage.success(res.data)
      getList()
    }
  } finally {
    syncLoading.value = false
    syncDialog.value = false
  }
}
const syncData = () => {
  actionType.value = 'sync'
  currentRow.value = undefined
  syncDialog.value = true
}

// 删除任务
const delLoading = ref(false)
const delData = async (row: TaskType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TaskType) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

// excel导入
const importList = () => {
  dialogTitle.value = '导入依赖数据'
  actionType.value = 'import'
  currentRow.value = undefined
  dialogVisible.value = true
}

// excel导出
</script>

<template>
  <div class="flex w-full h-full">
    <ContentWrap class="w-300px mr-5px" :class="collapseBtnClass">
      <div class="flex justify-center items-center">
        <ElInput v-model="currentGroup" class="flex-[4]" placeholder="搜索分组" clearable />
      </div>
      <ElDivider />
      <ElTree
        ref="treeEl"
        :data="groupTree"
        :expand-on-click-node="false"
        node-key="id"
        :props="{
          label: 'name'
        }"
        highlight-current
        :filter-node-method="filterNode"
        @current-change="currentChange"
        class="overflow-y-scroll min-h-100 max-h-screen"
      >
        <template #default="{ data }">
          <div
            :title="data.name"
            class="whitespace-nowrap overflow-ellipsis overflow-hidden w-full flex items-center"
          >
            <p>{{ data.name }}</p>
            <p class="ml-auto text-[10px] font-thin">{{ data.progress }}</p>
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3]">
      <ElButton class="absolute top-50% left-0" @click="isCollpase = !isCollpase" plain>
        <Icon icon="fad:h-expand" />
      </ElButton>
      <Search
        :schema="searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
        @register="formRegister"
        :show-expand="true"
        expand-field="plan_user"
      />

      <div class="mb-10px">
        <ElButton type="primary" @click="importList">上传</ElButton>
        <ElButton type="primary" @click="syncData">同步</ElButton>
        <ElButton type="primary" @click="() => exportQueryList()">导出</ElButton>
        <ElButton :loading="delLoading" type="danger" @click="delData(null)">
          {{ t('common.del') }}
        </ElButton>
      </div>
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <TicketTable v-if="actionType === 'add'" ref="writeRef" />
      <Write v-else-if="actionType === 'edit'" ref="writeRef" :current-row="currentRow" />
      <Import v-else-if="actionType === 'import'" />
      <template #footer>
        <ElButton type="primary" :loading="saveLoading" @click="save" v-if="actionType != 'import'">
          {{ t('common.save') }}
        </ElButton>
        <ElButton @click="dialogVisible = false">{{ t('common.close') }}</ElButton>
      </template>
    </Dialog>
    <Dialog v-model="syncDialog" title="同步任务" width="600px" max-height="400px">
      <Sync v-if="actionType === 'sync'" ref="writeRef" />
      <template #footer>
        <ElButton type="primary" :loading="syncLoading" @click="syncTasks">
          {{ t('common.save') }}
        </ElButton>
        <ElButton @click="syncDialog = false">{{ t('common.close') }}</ElButton>
      </template>
    </Dialog>
  </div>
</template>

<style lang="less" scoped>
.el-tree-unfold {
  display: none;
}
</style>
